import {EntityState, createEntityAdapter} from '@ngrx/entity';
import {createReducer, createSelector, on} from '@ngrx/store';
import {ListActions} from '../actions/list.actions';

// 定义实体的接口
export interface Entity {
  id: number;
  name: string;
  age: number
}

// 创建实体适配器
export const entityAdapter = createEntityAdapter<Entity>( {selectId: (entity: Entity) => entity.id});

const initialState: EntityState<Entity> = entityAdapter.getInitialState({
  ids: [1, 2, 3], // 设置初始的实体ID数组
  entities: {
    1: {id: 1, name: "Entity 1", age: 20},
    2: {id: 2, name: "Entity 2", age: 25},
    3: {id: 3, name: "Entity 3", age: 30}
  }
});

// const initialState: EntityState<Entity> = entityAdapter.getInitialState();

// selectTotal 获取数据条数
// selectAll 获取所有数据 以数组形式呈现
// selectEntities 获取实体集合 以字典形式呈现
// selectIds 获取id集合, 以数组形式呈现
export const { selectIds, selectEntities, selectAll, selectTotal } = entityAdapter.getSelectors();

let counter = 3;

function generateId() {
  return ++counter;
}

// 创建reducer
export const entityListReducer = createReducer(
  initialState,
  on(ListActions.addEntity, (state, {data}) => {
    const id = generateId()
    console.log(entityAdapter)
    return entityAdapter.addOne({id, ...data}, state)
  }),
  on(ListActions.removeEntity, (state, {data}) => {
    return entityAdapter.removeOne(data.id, state)
  }),
  on(ListActions.updateEntity, (state, {data}) => {
    return entityAdapter.upsertOne(data, state)
  }),
  on(ListActions.removeMultipleEntity, (state, {data}) => {
    let arrId = data.map((v: { id: number; }) => v.id);
    return entityAdapter.removeMany(arrId, state)
  })
)

